<?php

//运单控制器
class WaybilllessApp extends BackendApp
{
	var $_waybill_mod;
	var $_dictionary_mod;
	var $_user_mod;
	var $canedit;
	var $_haul_mod;
	function __construct()
	{
		$this->WaybilllessApp();
	}

	function WaybilllessApp()
	{
		parent::BackendApp();

		$this->_waybill_mod =& m('waybill');
		$this->_dictionary_mod =& m('dictionary');
		$this->_user_mod =& m('member');
		$this->_haul_mod =& m('haul');
		$this->canedit=false;
	}

	function index()
	{
		$db=&db();
		$sql="SELECT d_value FROM zys_dictionary WHERE d_code='wstatus'";
		$wstatus=$db->getAll($sql);
		$status=array();
		foreach ($wstatus as  $v){
			$status[$v['d_value']]=$v['d_value'];
		}
		$this->assign('status', $status);

		$wm_carrier=empty($_GET['wm_carrier'])?'':$_GET['wm_carrier'];
		$type_id=empty($_GET['type_id'])?'':$_GET['type_id'];
		$mstatus=empty($_GET['status'])?'':$_GET['status'];
		$conditions = "1=1 and wm_type='零担'";
		if($wm_carrier){
			$conditions.=" and wm_carrier LIKE '%".$wm_carrier."%'";
		}
		if($type_id){
			$conditions.="  AND wm_type ='".$type_id."'";
		}
		if($mstatus!=null&&$mstatus!=''){
			$conditions.=" and wm_stauts='".$mstatus."' ";
		}
		$user_ids = $this->checkpower();
		if(!empty($user_ids)){
			$conditions.=" and wm_optid in(".$user_ids.")";
		}
		$page   =   $this->_get_page(10);   //获取分页信息


		$waybill=$this->_waybill_mod->find(array(
	        'fields'   => 'this.*,member.user_name', 
		    'conditions'  => $conditions,
	        'limit'   => $page['limit'],
			'order'   => 'wm_tid desc',
			'join'=>'belongs_to_user',
        	'count'   => true   //允许统计
		));    //找出所有的运单
		$page['item_count']=$this->_waybill_mod->getCount();   //获取统计数据

		$this->assign('canedit', $this->canedit);

		$this->_format_page($page);
		//var_dump($page);exit;
		$this->assign('page_info', $page);   //将分页信息传递给视图，用于形成分页条
		$this->assign('waybill', $waybill);
		$this->import_resource(array('script' => 'inline_edit.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
                                      'style'=> 'jquery.ui/themes/ui-lightness/jquery.ui.css'));

		$this->assign('tabself', json_encode(array('text'=>'整车运单')));
		$this->display('waybill.less.index.html');
	}


	//新增
	function add()
	{

		$db=&db();
		if (!IS_POST)
		{
			$db=&db();
			$sql="select * from zys_operator where o_consignor=1";
			$huo=$db->getAll($sql);
			$h=array();
			foreach ($huo as $v){
				$h[$v['o_tid']]=$v['o_name'];
			}

			$this->assign('h', $h);

			$d_valuewaybill=$this->_dictionary_mod->get(array(
	        'fields'   => 'this.d_value',
	        'conditions'  => "d_key='wm_check_interval'",
			));

			$waybill=array();
			$waybill['wm_stauts']='新建';
			$waybill['wm_type']='零担';
			$waybill['wm_code']=$this->autocode();
			$waybill['wm_check_interval']= $d_valuewaybill['d_value'];
			$waybill['wm_opdate']=  gmtime();

			$waybill['user_name']=$this->visitor->get('user_name');

			$this->assign('canedit', true);
			$this->assign('cannew', true);
			$this->assign('canyy', true);
			$this->assign('sub', array(0=>array('g_tid'=>0)));


			$gt=array();
			$goodstype=$this->_dictionary_mod->find(array(
	        'fields'   => 'this.d_value',
	        'conditions'  => "d_code='goodstype'",
			));

			if($goodstype){
				foreach($goodstype as $v){
					$gt[$v['d_value']]=$v['d_value'];
				}
			}
			$this->assign('goodstype', $gt);

			/* 导入jQuery的表单验证插件 */
			$this->import_resource(array('script' => 'inline_edit.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js,jquery.plugins/jquery.validate.js',
        'style'=> 'jquery.ui/themes/ui-lightness/jquery.ui.css'));


			$this->assign('waybill', $waybill);
			$this->assign('tabself', json_encode(array('text'=>'新建运单')));
			$this->assign('tabback', json_encode(array('text'=>'整车运单','url'=>'')));
			$this->display('waybill.less.form.html');

		}else {

			$normal=empty($_POST['normal'])?array():$_POST['normal'];

			if(!$normal){
				$this->show_warning('添加运单失败，请重试',
                '',   'index.php?app=waybillless&act=add');
				return;
			}
			$normal=array_values($normal);
			foreach ($normal as $k=>$v){
				$g_tid=0;

				$sql="insert into zys_goods_normal set g_ownertid='".$v['g_ownertid']."',g_owner='".$v['g_owner']."',
					g_owner_tel='".$v['g_owner_tel']."',g_loading_place='".$v['g_loading_place']."',
					g_loading_lng='".$v['g_loading_lng']."',g_loading_lat='".$v['g_loading_lat']."',g_unloading_place='".$v['g_unloading_place']."',
					g_unloading_lng='".$v['g_unloading_lng']."',g_unloading_lat='".$v['g_unloading_lat']."',g_consignee='".$v['g_consignee']."',
					g_consignee_tel='".$v['g_consignee_tel']."',g_consignor='".$v['g_consignor']."',g_consignor_tel='".$v['g_consignor_tel']."',
					g_note='".$v['g_note']."',g_gtype='".$v['g_gtype']."',g_loading_date='".gmstr2time($v['g_loading_date'])."',g_unloading_date='".gmstr2time($v['g_unloading_date'])."',
					g_optid='".$this->visitor->get('user_id')."',g_opdate='".gmtime()."',g_code='T".gmtime()."',g_type='零担'";

				$db->query($sql);
				$g_tid=$db->insert_id();
				$userid = $this->visitor->get('user_id');
				$unit = $this->visitor->get('unit');
				$num = $this->checkaddr($v['g_loading_place'],$userid,$unit);
				if($num==0){
					$loading = array(
						'user_id'    	=>	$userid,
						'consignee' 	=>	$v['g_consignor'],
						'address' 		=>	$v['g_loading_place'],
						'phone_tel'	=>	$v['g_consignor_tel'],
						'lng'			=>	$v['g_loading_lng'],
						'lat'			=>	$v['g_loading_lat'],
						'addrtype'		=>	'零担装货',
						'unit'			=>	$unit,
					);
					$this->addaddr($loading);
				}
				$num1 = $this->checkaddr($v['g_unloading_place'],$userid,$unit);
				if($num1==0){
					$unloading = array(
						'user_id'    	=>	$userid,
						'consignee' 	=>	$v['g_consignee'],
						'address' 		=>	$v['g_unloading_place'],
						'phone_tel'	=>	$v['g_consignee_tel'],
						'lng'			=>	$v['g_unloading_lng'],
						'lat'			=>	$v['g_unloading_lat'],
						'addrtype'		=>	'零担卸货',
						'unit'			=>	$unit,
					);
					$this->addaddr($unloading);
				}
					
				if(empty($wid)){
					$data = array(
                'wm_stauts'  => '新建',
                'wm_type'  => '零担',
                'wm_code' => $_POST['wm_code'],
				'wm_opdate'=> gmtime(),
			    'wm_optid'=> $this->visitor->get('user_id'),
					);

					$wid = $this->_waybill_mod->add($data);
				}

				if($v['item']){
					$v['item']=array_values($v['item']);
					foreach ($v['item'] as $kk=>$vv){

						$sql="insert into zys_goods_normal_sub set gs_gtid='".$g_tid."',gs_name='".$vv['gs_name']."',gs_piece='".$vv['gs_piece']."',
								gs_size='".$vv['gs_size']."',gs_weight='".$vv['gs_weight']."',gs_piecep='".$vv['gs_piece']."',gs_weightp='".$vv['gs_weight']."'
								,gs_sizep='".$vv['gs_sizep']."',g_consignor='".$v['g_ownertid']."',g_viewer='".$v['g_ownertid']."'";
						$db->query($sql);

						$gs_tid=$db->insert_id();

						$sql="insert into zys_waybill_sub_normal set ws_wmtid='".$wid."',ws_gid='".$g_tid."',ws_gstid='".$gs_tid."',
				ws_piece='".$vv['gs_piece']."',ws_weight='".$vv['gs_weight']."',ws_size='".$vv['gs_size']."'";
						$db->query($sql);
					}
				}
			}

			$this->show_message('添加运单成功',
                '添加运单成功',   'index.php?app=waybillless&act=edit&id='.$wid
			);

		}

	}


	//编辑
	function edit()
	{
		$db=&db();
		$id = empty($_GET['id']) ? 0 : intval($_GET['id']);
		$waybill=$this->_waybill_mod->get(array(
	        'fields'   => 'this.*',
	        'conditions'  => 'wm_tid='.$id,
		));
		if($waybill['wm_stauts']=='新建'||$waybill['wm_stauts']=='已接单'||$waybill['wm_stauts']=='已派'){
			$this->canedit=true;
		}
		if (!IS_POST)
		{
			//异常信息
			$exception=array();
			$sql="SELECT * FROM zys_exception WHERE e_w_tid=$id";
			$exception=$db->getAll($sql);
			if($exception){
				foreach ($exception as $k=>$v){
					$sql="SELECT * FROM zys_exception_attr WHERE ea_type=0 and ea_e_tid=".$v['e_tid'];
					$exception[$k]['e_pic']=$db->getAll($sql);

					$sql="SELECT * FROM zys_exception_attr WHERE ea_type!=0 and ea_e_tid=".$v['e_tid'];
					$exception[$k]['e_voice']=$db->getAll($sql);
				}
			}
			$this->assign('exception', $exception);

			//------------------编辑状态下运营商列表start--------------------
			$sql="SELECT * FROM zys_operator WHERE o_carrier=1";
			$oper=$db->getAll($sql);
			$oarray=array();
			foreach ($oper as $v){
				$oarray[$v['o_tid']]=$v['o_name'];
			}

			$this->assign('oper', $oarray);
			//------------------编辑状态下运营商列表end----------------------

			$waybill=$this->_waybill_mod->get(array(
	        'fields'   => 'this.*,member.user_name',
	        'conditions'  => 'wm_tid='.$id,
			'join'=>'belongs_to_user',
			));

			$types=array();
			$types['集卡进口'] = '集卡进口';
			$types['集卡出口'] = '集卡出口';
			$types['整车'] = '整车';
			$types['零担'] = '零担';
			$types['城配'] = '城配';
			$this->assign('search_options', $types);

			$this->assign('id', $id);
			$this->assign('waybill', $waybill);


			$this->assign('canedit', $this->canedit);
			$this->assign('wm_id', $waybill['wm_tid']);


			/* 导入jQuery的表单验证插件 */
			$this->import_resource(array('script' => 'inline_edit.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js,jquery.plugins/jquery.validate.js',
        	'style'=> 'jquery.ui/themes/ui-lightness/jquery.ui.css'));

			$this->assign('tabself', json_encode(array('text'=>'编辑运单')));
			$this->assign('tabback', json_encode(array('text'=>'运单管理','url'=>'')));

			$cannew=true;
			$canyy=true;

			$sql="SELECT * from zys_waybill_sub_normal w
LEFT JOIN zys_goods_normal_sub g on w.ws_gstid=g.gs_tid
LEFT JOIN zys_goods_normal t on t.g_tid=g.gs_gtid where 	
ws_wmtid=".$id;

			$sub=$db->getAll($sql);
			$sublist=array();
			if($sub){
				foreach ($sub as $v){

					if($v['ws_new']){
						$sublist[$v['gs_gtid']]['new']=1;
						$this->canedit=false;
					}else{
						$sublist[$v['gs_gtid']]['new']=0;
						$canyy=false;
					}
					$sublist[$v['gs_gtid']]['g_tid']=$v['g_tid'];
					$sublist[$v['gs_gtid']]['g_ownertid']=$v['g_ownertid'];
					$sublist[$v['gs_gtid']]['g_owner']=$v['g_owner'];
					$sublist[$v['gs_gtid']]['g_owner_tel']=$v['g_owner_tel'];
					$sublist[$v['gs_gtid']]['g_loading_place']=$v['g_loading_place'];
					$sublist[$v['gs_gtid']]['g_loading_lng']=$v['g_loading_lng'];
					$sublist[$v['gs_gtid']]['g_loading_lat']=$v['g_loading_lat'];
					$sublist[$v['gs_gtid']]['g_unloading_place']=$v['g_unloading_place'];
					$sublist[$v['gs_gtid']]['g_loading_date']=$v['g_loading_date'];
					$sublist[$v['gs_gtid']]['g_unloading_date']=$v['g_unloading_date'];
					$sublist[$v['gs_gtid']]['g_unloading_lng']=$v['g_unloading_lng'];
					$sublist[$v['gs_gtid']]['g_unloading_lat']=$v['g_unloading_lat'];
					$sublist[$v['gs_gtid']]['g_consignee']=$v['g_consignee'];
					$sublist[$v['gs_gtid']]['g_consignee_tel']=$v['g_consignee_tel'];
					$sublist[$v['gs_gtid']]['g_gtype']=$v['g_gtype'];

					$sublist[$v['gs_gtid']]['g_consignor']=$v['g_consignor'];
					$sublist[$v['gs_gtid']]['g_consignor_tel']=$v['g_consignor_tel'];
					//$sublist[$v['gs_gtid']]['g_tgdate']=$v['g_tgdate'];
					//$sublist[$v['gs_gtid']]['g_rdate']=$v['g_rdate'];
					$sublist[$v['gs_gtid']]['g_note']=$v['g_note'];

					$sublist[$v['gs_gtid']]['box'][]=$v;
				}
			}
			$this->assign('cannew', $cannew);
			$this->assign('canyy', $canyy);
			if(empty($sublist)){
				$sublist=array(0=>array('g_tid'=>0));
			}
			$this->assign('sub', $sublist);

			$monitor=array();
			$sql="select * from zys_monitor_main";
			$m=$db->getAll($sql);
			if($m){
				foreach ($m as $v){
					$monitor[$v['zmm_tid']]=$v['zmm_name'];
				}
			}
			$this->assign('monitor', $monitor);

			$hauldefine=array();
			$sql="select * from zys_haul_define_main where zhdm_type='".$waybill['wm_type']."'";
			$h=$db->getAll($sql);
			if($h){
				foreach ($h as $v){
					$hauldefine[$v['zhdm_tid']]=$v['zhdm_name'];
				}
			}
			$this->assign('hauldefine', $hauldefine);

			$sql="SELECT d_value,d_key FROM zys_dictionary WHERE d_code='haultype'";
			$typelist=array();
			$temp=$db->getAll($sql);

			foreach ($temp as $v){
				$typelist[$v['d_key']]=$v['d_value'];
			}
			$this->assign('typelist', $typelist);

			$sql="SELECT d_value,d_key FROM zys_dictionary WHERE d_code='h_collect_type'";
			$typelist=array();
			$temp=$db->getAll($sql);

			foreach ($temp as $v){
				$typelist[$v['d_key']]=$v['d_value'];
			}
			$this->assign('ctype', $typelist);

			$haullist=array();
			$sql="SELECT * from zys_haul where h_wmtid=".$id." ORDER BY h_order";
			$haul=$db->getAll($sql);

			$haullist=array();
			if($haul){
				foreach ($haul as $v){
					$sql="SELECT * from zys_haul_collect WHERE hc_h_tid=".$v['h_tid'];
					$collect=$db->getAll($sql);
					if($collect){
						foreach ($collect as $vv){
							$arrs=array();
							if($vv['h_collect_val']){
								$vv['h_collect_val']=trim($vv['h_collect_val'],',');
								$arrs=explode(',', $vv['h_collect_val']);
							}
							$vv['ar']=$arrs;
							$v['item'][]=$vv;
						}
					}

					$haullist[]=$v;
				}
			}

			$this->assign('haullist', $haullist);

			$gt=array();
			$goodstype=$this->_dictionary_mod->find(array(
	        'fields'   => 'this.d_value',
	        'conditions'  => "d_code='goodstype'",
			));

			if($goodstype){
				foreach($goodstype as $v){
					$gt[$v['d_value']]=$v['d_value'];
				}
			}
			$this->assign('goodstype', $gt);
				
			$this->display('waybill.less.form.html');
		}else
		{
			$sql='select wm_version from zys_waybill_main where wm_tid='.$id;
			$wm_version = $this->_waybill_mod->getOne($sql);

			if(intval($wm_version)<=0){
				$wm_version=0;
			}
			$wm_version=$wm_version+1;


			if($this->canedit){

				$normal=empty($_POST['normal'])?array():$_POST['normal'];

				if(!$normal){
					$this->show_warning('编辑运单失败，请重试' , '',   'index.php?app=waybillless&act=edit&id=' . $id);
					return;
				}
				$userid = $this->visitor->get('user_id');
				$unit = $this->visitor->get('unit');
				$normal=array_values($normal);
				foreach ($normal as $k=>$v){
					$g_tid=0;
					if(empty($v['g_tid'])){
						$sql="insert into zys_goods_normal set g_ownertid='".$v['g_ownertid']."',g_owner='".$v['g_owner']."',
					g_owner_tel='".$v['g_owner_tel']."',g_loading_place='".$v['g_loading_place']."',
					g_loading_lng='".$v['g_loading_lng']."',g_loading_lat='".$v['g_loading_lat']."',g_unloading_place='".$v['g_unloading_place']."',
					g_unloading_lng='".$v['g_unloading_lng']."',g_unloading_lat='".$v['g_unloading_lat']."',g_consignee='".$v['g_consignee']."',
					g_consignee_tel='".$v['g_consignee_tel']."',g_consignor='".$v['g_consignor']."',g_consignor_tel='".$v['g_consignor_tel']."',g_note='".$v['g_note']."'
					,g_loading_date='".gmstr2time($v['g_loading_date'])."',g_unloading_date='".gmstr2time($v['g_unloading_date'])."',g_gtype='".$v['g_gtype']."',
					g_optid='".$this->visitor->get('user_id')."',g_opdate='".gmtime()."',g_code='T".gmtime()."',g_type='零担'";

						$db->query($sql);
						$g_tid=$db->insert_id();
						$num = $this->checkaddr($v['g_loading_place'],$userid,$unit);
						if($num==0){
							$loading = array(
								'user_id'    	=>	$userid,
								'consignee' 	=>	$v['g_consignor'],
								'address' 		=>	$v['g_loading_place'],
								'phone_tel'	=>	$v['g_consignor_tel'],
								'lng'			=>	$v['g_loading_lng'],
								'lat'			=>	$v['g_loading_lat'],
								'addrtype'		=>	'零担装货',
								'unit'			=>	$unit,
							);
							$this->addaddr($loading);
						}
						$num1 = $this->checkaddr($v['g_unloading_place'],$userid,$unit);
						if($num1==0){
							$unloading = array(
								'user_id'    	=>	$userid,
								'consignee' 	=>	$v['g_consignee'],
								'address' 		=>	$v['g_unloading_place'],
								'phone_tel'	=>	$v['g_consignee_tel'],
								'lng'			=>	$v['g_unloading_lng'],
								'lat'			=>	$v['g_unloading_lat'],
								'addrtype'		=>	'零担卸货',
								'unit'			=>	$unit,
							);
							$this->addaddr($unloading);
						}

					}else{
						$g_tid=$v['g_tid'];
						$num = $this->checkaddr($v['g_loading_place'],$userid,$unit);
						if($num==0){
							$loading = array(
								'user_id'    	=>	$userid,
								'consignee' 	=>	$v['g_consignor'],
								'address' 		=>	$v['g_loading_place'],
								'phone_tel'	=>	$v['g_consignor_tel'],
								'lng'			=>	$v['g_loading_lng'],
								'lat'			=>	$v['g_loading_lat'],
								'addrtype'		=>	'零担装货',
								'unit'			=>	$unit,
							);
							$this->addaddr($loading);
						}
						$num1 = $this->checkaddr($v['g_unloading_place'],$userid,$unit);
						if($num1==0){
							$unloading = array(
								'user_id'    	=>	$userid,
								'consignee' 	=>	$v['g_consignee'],
								'address' 		=>	$v['g_unloading_place'],
								'phone_tel'	=>	$v['g_consignee_tel'],
								'lng'			=>	$v['g_unloading_lng'],
								'lat'			=>	$v['g_unloading_lat'],
								'addrtype'		=>	'零担卸货',
								'unit'			=>	$unit,
							);
							$this->addaddr($unloading);
						}
						$sql="update zys_goods_normal set g_ownertid='".$v['g_ownertid']."',g_owner='".$v['g_owner']."',
					g_owner_tel='".$v['g_owner_tel']."',g_loading_place='".$v['g_loading_place']."',
					g_loading_lng='".$v['g_loading_lng']."',g_loading_lat='".$v['g_loading_lat']."',g_unloading_place='".$v['g_unloading_place']."',
					g_unloading_lng='".$v['g_unloading_lng']."',g_unloading_lat='".$v['g_unloading_lat']."',g_consignee='".$v['g_consignee']."',
					g_consignee_tel='".$v['g_consignee_tel']."',g_consignor='".$v['g_consignor']."',g_consignor_tel='".$v['g_consignor_tel']."',g_note='".$v['g_note']."'
					,g_loading_date='".gmstr2time($v['g_loading_date'])."',g_unloading_date='".gmstr2time($v['g_unloading_date'])."',g_gtype='".$v['g_gtype']."'
					where g_tid=".$g_tid;

						$db->query($sql);
					}

					if($v['item']){
						$v['item']=array_values($v['item']);
						foreach ($v['item'] as $kk=>$vv){
							if($vv['gs_tid']){
								$gs_tid=$vv['gs_tid'];
								$sql="update zys_goods_normal_sub set gs_name='".$vv['gs_name']."',gs_piece='".$vv['gs_piece']."',
								gs_size='".$vv['gs_size']."',gs_weight='".$vv['gs_weight']."',gs_piecep='".$vv['gs_piece']."',gs_weightp='".$vv['gs_weight']."'
								,gs_sizep='".$vv['gs_sizep']."',g_consignor='".$v['g_ownertid']."',g_viewer='".$v['g_ownertid']."' where gs_tid=".$gs_tid;
								$db->query($sql);

								$sql="update zys_waybill_sub_normal set
				ws_piece='".$vv['gs_piece']."',ws_weight='".$vv['gs_weight']."',ws_size='".$vv['gs_size']."' where ws_wmtid='".$id."' and ws_gid='".$g_tid."' and ws_gstid='".$gs_tid."'";
								$db->query($sql);
							}else{
								$sql="insert into zys_goods_normal_sub set gs_gtid='".$g_tid."',gs_name='".$vv['gs_name']."',gs_piece='".$vv['gs_piece']."',
								gs_size='".$vv['gs_size']."',gs_weight='".$vv['gs_weight']."',gs_piecep='".$vv['gs_piece']."',gs_weightp='".$vv['gs_weight']."'
								,gs_sizep='".$vv['gs_sizep']."',g_consignor='".$v['g_ownertid']."',g_viewer='".$v['g_ownertid']."'";
								$db->query($sql);

								$gs_tid=$db->insert_id();

								$sql="insert into zys_waybill_sub_normal set ws_wmtid='".$id."',ws_gid='".$g_tid."',ws_gstid='".$gs_tid."',
				ws_piece='".$vv['gs_piece']."',ws_weight='".$vv['gs_weight']."',ws_size='".$vv['gs_size']."'";
								$db->query($sql);
							}
						}
					}

				}


				$data = array(
                'wm_version' => $wm_version
				);

				$this->_waybill_mod->edit($id,$data);

				$this->show_message('edit_ok',
                '返回运单',   'index.php?app=waybillless&act=edit&id=' . $id
				);
			}else{
				$this->show_warning('不能修改此运单' ,'',   'index.php?app=waybillless&act=edit&id=' . $id);
				return;
			}
		}
	}

	function hauledit(){
		$db=&db();
		$id=empty($_POST['wm_tid'])?0:intval($_POST['wm_tid']);
		$waybill=$this->_waybill_mod->get(array(
	        'fields'   => 'this.*',
	        'conditions'  => 'wm_tid='.$id,
		));

		if($waybill['wm_stauts']!='新建'&&$waybill['wm_stauts']!='已接单'&&$waybill['wm_stauts']!='已派'){
			$this->show_warning('运单不能修改', '',   'index.php?app=waybillless&act=edit&id='.$id);
			return;
		}

		$haul=empty($_POST['haul'])?array():$_POST['haul'];

		if($haul){
			$haul=array_values($haul);
			foreach ($haul as $k=>$v){
				$h_tid = 0;
				if($v['h_tid']) {
					$h_tid = $v['h_tid'];
					$sql = "update zys_haul set h_name='" . $v['h_name'] . "',h_linkman='" . $v['h_linkman'] . "',
					h_linkman_tel='" . $v['h_linkman_tel'] . "',h_type='" . $v['h_type'] . "',h_range='" . intval($v['h_range']) . "',h_required_service_date='" . gmstr2time($v['h_required_service_date']) . "',
					h_note='" . $v['h_note'] . "',h_address='" . $v['h_address'] . "',h_lat='" . $v['h_lat'] . "',h_lng='" . $v['h_lng'] . "' where h_tid=" . $v['h_tid'];

					$db->query($sql);
				}
				else{
					$data['h_wmtid'] = $id;
					$data['h_name'] = $v['h_name'];
					$data['h_short_name'] = $v['h_name'];
					$data['h_linkman'] = $v['h_linkman'];
					$data['h_linkman_tel'] = $v['h_linkman_tel'];
					$data['h_address'] = $v['h_address'];
					$data['h_order'] = 255;
					$data['h_type'] = $v['h_type'];
					$data['h_range'] = intval($v['h_range']);
					$data['h_required_service_date'] = gmstr2time($v['h_required_service_date']);
					$data['h_note'] = $v['h_note'];
					$data['h_lat'] = $v['h_lat'];
					$data['h_lng'] = $v['h_lng'];
					$h_tid = $this->_haul_mod->add($data);
				}
					if($v['item']){
						$v['item']=array_values($v['item']);
						foreach ($v['item'] as $kk=>$vv){
							if($vv['hc_tid']){
								$sql="update zys_haul_collect set h_collect_type='".$vv['h_collect_type']."',h_collect_des='".$vv['h_collect_des']."' where hc_tid=".$vv['hc_tid'];
								$db->query($sql);
							}else{
								$sql="insert into zys_haul_collect set hc_h_tid='".$h_tid."',
						h_collect_type='".$vv['h_collect_type']."',h_collect_des='".$vv['h_collect_des']."'";
								$db->query($sql);
							}
						}
					}
			}
		}

		$this->show_message('编辑运程成功',
                '返回运单',   'index.php?app=waybillless&act=edit&id='.$id
		);
	}
	//监控方案
	function monitor(){
		$db=&db();
		$id = empty($_POST['id']) ? 0 : intval($_POST['id']);
		$mid = empty($_POST['mid']) ? 0 : intval($_POST['mid']);
		$waybill=$this->_waybill_mod->get(array(
			'fields'   => 'this.*',
			'conditions'  => 'wm_tid='.$id,
		));

		if($waybill['wm_stauts']!='新建'&&$waybill['wm_stauts']!='已接单'){
			$this->show_warning('运单不能修改','',   'index.php?app=waybill&act=edit&id='.$id);
			return;
		}

		$data = array('wm_zmmtid'  => $mid);

		$wid = $this->_waybill_mod->edit($id,$data);
		//返回数据
		$this->json_result($data,'选择监控方案成功');
	}

	function hauldefine(){
		$db=&db();
		$id = empty($_GET['id']) ? 0 : intval($_GET['id']);
		$hid = empty($_GET['hid']) ? 0 : intval($_GET['hid']);

		$waybill=$this->_waybill_mod->get(array(
	        'fields'   => 'this.*',
	        'conditions'  => 'wm_tid='.$id,
		));

		if($waybill['wm_stauts']!='新建'&&$waybill['wm_stauts']!='已接单'&&$waybill['wm_stauts']!='已派'){
			$this->show_warning('运单不能修改', '',   'index.php?app=waybillless&act=edit&id='.$id);
			return;
		}

		$this->addhauldeploy($hid,$id);

		$this->show_message('选择进程方案成功',
                '返回运单',   'index.php?app=waybillless&act=edit&id='.$id
		);
	}

	function delsub(){
		try{
			$db=&db();
			$id = empty($_POST['id']) ? 0:intval($_POST['id']);

			if(empty($id)){
				throw new Exception('操作失败');
			}

			$sql="select * from zys_waybill_sub_normal t left join zys_waybill_main m on t.ws_wmtid=m.wm_tid  where ws_tid=".$id;
			$sub=$db->getRow($sql);

			if(($sub['wm_stauts']!='新建'&&$sub['wm_stauts']!='已接单'&&$sub['wm_stauts']!='已派')||$sub['ws_new']==1){
				throw new Exception('操作失败');
			}

			$id=empty($sub['ws_gstid'])?0:intval($sub['ws_gstid']);
			$sql="select gs_gtid from zys_goods_normal_sub where gs_tid=".$id;
			$gs_gtid=$db->getOne($sql);

			$gs_gtid=empty($gs_gtid)?0:intval($gs_gtid);

			$sql="delete from zys_goods_normal_sub where gs_tid=".$id;
			$db->query($sql);

			$sql="delete from zys_waybill_sub_normal where ws_gstid=".$id." and ws_new=0";
			$db->query($sql);

			$sql="select count(1) from zys_goods_normal_sub where gs_gtid=".$gs_gtid;
			$c=$db->getOne($sql);
			if(empty($c)){
				$sql="delete from zys_goods_normal where g_tid=".$gs_gtid;
				$db->query($sql);
			}

			$this->json_result(array(),'删除成功');
		}catch (Exception $e){
			$this->json_error($e->getMessage());
		}
	}

	function del(){
		try{
			$db=&db();
			$id = empty($_POST['id']) ? 0:intval($_POST['id']);
			$wid = empty($_POST['wid']) ? 0:intval($_POST['wid']);

			if(empty($id)){
				throw new Exception('操作失败');
			}

			if(empty($wid)){
				throw new Exception('操作失败');
			}

			$sql="select * from zys_waybill_main where wm_tid=".$wid;
			$sub=$db->getRow($sql);

			if(($sub['wm_stauts']!='新建'&&$sub['wm_stauts']!='已接单'&&$sub['wm_stauts']!='已派')||$sub['ws_new']==1){
				throw new Exception('操作失败');
			}

			$sql="delete from zys_goods_normal_sub where gs_gtid=".$id;
			$db->query($sql);

			$sql="delete from zys_waybill_sub_normal where ws_gid='".$id."'";
			$db->query($sql);


			$sql="delete from zys_goods_normal where g_tid=".$id;
			$db->query($sql);

			$this->json_result(array(),'删除成功');
		}catch (Exception $e){
			$this->json_error($e->getMessage());
		}
	}


	function subadd(){

		$id = empty($_POST['ws_wmtid']) ? 0 : intval($_POST['ws_wmtid']);
		$waybill=$this->_waybill_mod->get(array(
	        'fields'   => 'this.*',
	        'conditions'  => 'wm_tid='.$id,
		));
		if($waybill['wm_stauts']=='新建'||$waybill['wm_stauts']=='已接单'){
			$this->canedit=true;
		}

		$s_mod =& m('waybilltrunk');
		$data = array(
                'ws_wmtid'  => $_POST['ws_wmtid'],
                'ws_type'  => $_POST['ws_type'],
                'ws_box' => $_POST['ws_box'],
                'ws_volume'	     => $_POST['ws_volume'],
			    'ws_ctn_no'      => $_POST['ws_ctn_no'],

			  'ws_eir_code'	     => $_POST['ws_eir_code'],
			    'ws_awb_code'      => $_POST['ws_awb_code'],
				 'ws_ship'      => $_POST['ws_ship'],

			  'ws_voyage'	     => $_POST['ws_voyage'],
			    'ws_container_depot'      => $_POST['ws_container_depot'],

			  'ws_full_container_depot'	     => $_POST['ws_full_container_depot'],
			    'ws_note'      => $_POST['ws_note'],

		);

		if($this->canedit){
			if($_POST['ws_tid']){
				$msg="修改集装箱成功";
				$s_mod->edit($_POST['ws_tid'],$data);
			}else{
				/* 保存 */
				$msg="添加集装箱成功";
				$rows = $s_mod->add($data);
			}
			$db=&db();

			$db=&db();
			if($_POST['ws_wmtid']>0){
				$sql="UPDATE zys_waybill_main w left JOIN (SELECT GROUP_CONCAT(ws_ship) as ws_ship,GROUP_CONCAT(ws_voyage) as ws_voyage,GROUP_CONCAT(ws_awb_code) as ws_awb_code,ws_wmtid
			FROM zys_waybill_sub_trunk WHERE ws_wmtid=".$_POST['ws_wmtid']." GROUP BY ws_wmtid) x on w.wm_tid=x.ws_wmtid
			SET w.wm_ship=x.ws_ship,w.wm_voyage=x.ws_voyage,w.wm_awb_code=x.ws_awb_code WHERE w.wm_tid=".$_POST['ws_wmtid'];
				$db->query($sql);

				$sql="UPDATE zys_waybill_main SET wm_version=wm_version+1 WHERE wm_tid=".$_POST['ws_wmtid'];
				$db->query($sql);
			}

			$this->show_message($msg,

                '返回明细',    'index.php?app=waybillless&act=edit&id='.$_POST['ws_wmtid']
			);
		}else{
			$this->show_warning('不能修改此运单',    'index.php?app=waybillless&act=edit&id='.$_POST['ws_wmtid']);
		}
	}

	function subaddn(){

		$id = empty($_POST['ws_wmtid']) ? 0 : intval($_POST['ws_wmtid']);
		$waybill=$this->_waybill_mod->get(array(
	        'fields'   => 'this.*',
	        'conditions'  => 'wm_tid='.$id,
		));
		if($waybill['wm_stauts']=='新建'||$waybill['wm_stauts']=='已接单'||$waybill['wm_stauts']=='已派'){
			$this->canedit=true;
		}

		$s_mod =& m('waybillnormal');
		$data = array(
                'ws_wmtid'  => $_POST['ws_wmtid'],
                'ws_name'  => $_POST['ws_name'],
                'ws_piece' => $_POST['ws_piece'],
                'ws_weight'	     => $_POST['ws_weight'],
			    'ws_size'      => $_POST['ws_size'],

			  'ws_owner'	     => $_POST['ws_owner'],
			    'ws_owner_tel'      => $_POST['ws_owner_tel'],
				 'ws_loading_place'      => $_POST['ws_loading_place'],

			  'ws_unloading_place'	     => $_POST['ws_unloading_place'],
			    'ws_consignee'      => $_POST['ws_consignee'],

			  'ws_consignee_tel'	     => $_POST['ws_consignee_tel'],
			    'ws_consignor'      => $_POST['ws_consignor'],

			'ws_consignor_tel'	     => $_POST['ws_consignor_tel'],
			    'ws_note'      => $_POST['ws_note'],

		);
		if($this->canedit){


			if($_POST['ws_tid']){
				$msg="修改货物成功";
				$s_mod->edit($_POST['ws_tid'],$data);
			}else{
				/* 保存 */
				$msg="添加货物成功";
				$rows = $s_mod->add($data);
			}



			if($_POST['ws_wmtid']>0){
				$db=&db();
				$sql="UPDATE zys_waybill_main w left JOIN (SELECT SUM(IFNULL(ws_piece,0)) as ws_piece,SUM(IFNULL(ws_weight,0)) as ws_weight,SUM(IFNULL(ws_size,0)) as ws_size,ws_wmtid

			FROM zys_waybill_sub_normal WHERE ws_wmtid=".$_POST['ws_wmtid']." GROUP BY ws_wmtid) x on w.wm_tid=x.ws_wmtid
			SET w.wm_piece=x.ws_piece,w.wm_weight=x.ws_weight,w.wm_size=x.ws_size WHERE w.wm_tid=". $_POST['ws_wmtid'];

				/* 保存 */
				$db->query($sql);

				$sql="UPDATE zys_waybill_main SET wm_version=wm_version+1 WHERE wm_tid=".$_POST['ws_wmtid'];
				$db->query($sql);

			}


			$this->show_message($msg,

                '返回明细',    'index.php?app=waybillless&act=edit&id='.$_POST['ws_wmtid']
			);
		}else{
			$this->show_warning('不能修改此运单' , '',    'index.php?app=waybillless&act=edit&id='.$_POST['ws_wmtid']);
		}
	}
	/*function view(){
		$id = empty($_GET['id']) ? 0 : intval($_GET['id']);
		if (!IS_POST){
			$waybill=$this->_waybill_mod->get(array(
	        'fields'   => 'this.*,member.user_name',
	        'conditions'  => 'wm_tid='.$id,
			'join'=>'belongs_to_user',
			));

			$types=array();
			$types['集卡进口'] = '集卡进口';
			$types['集卡出口'] = '集卡出口';
			$types['整车'] = '整车';
			$types['零担'] = '零担';
			$types['城配'] = '城配';
			$this->assign('search_options', $types);

			$this->assign('id', $id);
			$this->assign('waybill', $waybill);


			$this->assign('canedit', $this->canedit);
			$this->assign('wm_id', $waybill['wm_tid']);




			$this->import_resource(array('script' => 'inline_edit.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js,jquery.plugins/jquery.validate.js',
        	'style'=> 'jquery.ui/themes/ui-lightness/jquery.ui.css'));

			$db=&db();
			$normal=true;

			if($waybill['wm_type']=='集卡进口'||$waybill['wm_type']=='集卡出口'){
				$normal=false;
			}
			$this->assign('normal', $normal);

			$sql="select * from zys_waybill_sub_normal where ws_wmtid=".$id;
			$sub_normal =$db->getAll($sql);
			$this->assign('sub_normal', $sub_normal);

			$sql="select * from zys_waybill_sub_trunk where ws_wmtid=".$id;
			$sub_trunk =$db->getAll($sql);
			$this->assign('sub_trunk', $sub_trunk);

			$this->display('waybill.view.html');
		}
	}*/

	//删除
	function drop()
	{
		$arr = isset($_GET['id']) ? trim($_GET['id']) : '';
		$db=&db();
		$arrs=explode(',', $arr);
		if($arrs!=null&&count($arrs)>0){
			foreach ($arrs as $v){
				$sql="SELECT wm_stauts FROM zys_waybill_main WHERE wm_tid=".$v;
				$status=$db->getOne($sql);
				if($status=='新建'||$status=='已接单'||$status=='已派'){
					//补回货物
					$sql="SELECT ifnull(SUM(ws_piece),0) as mpsum,ifnull(SUM(ws_weight),0) as mwsum,
					ifnull(SUM(ws_size),0) as mssum,ws_gstid from zys_waybill_sub_normal WHERE ws_wmtid=$v GROUP BY ws_gstid";
					$array=$db->getAll($sql);
					if($array){
						foreach ($array as $vv){
							//更新货单子表数据
							$sql="UPDATE zys_goods_normal_sub SET gs_piecep=(gs_piecep-".$vv['mpsum']."),
							gs_weightp=(gs_weightp-".$vv['mwsum']."),gs_sizep=(gs_sizep-".$vv['mssum'].")
							WHERE gs_tid=".$vv['ws_gstid'];
							$db->query($sql);
						}
					}



					if (!$this->_waybill_mod->drop($v))
					{
						$this->show_warning($this->_waybill_mod->get_error()  ,'',    'index.php?app=waybillless&act=index');
						return;
					}
				}
			}
		}else{
			$sql="SELECT wm_stauts FROM zys_waybill_main WHERE wm_tid=".$arr;
			$status=$db->getOne($sql);
			if($status=='新建'||$status=='已接单'){
				if (!$this->_waybill_mod->drop($arr))
				{
					$this->show_warning($this->_waybill_mod->get_error(),  '',    'index.php?app=waybillless&act=index');
					return;
				}
			}
		}
		$this->show_message('',

                '返回列表',    'index.php?app=waybillless&act=index'
                );
	}

	function dropsub()
	{
		$db=&db();
		$id = empty($_GET['wid']) ? 0 : intval($_GET['wid']);
		$waybill=$this->_waybill_mod->get(array(
	        'fields'   => 'this.*',
	        'conditions'  => 'wm_tid='.$id,
		));
		if($waybill['wm_stauts']=='新建'||$waybill['wm_stauts']=='已接单'||$waybill['wm_stauts']=='已派'){
			$this->canedit=true;
		}
		$s_mod =& m('waybilltrunk');
		$arr = isset($_GET['id']) ? trim($_GET['id']) : '';

		$arrs=explode(',', $arr);
		if($this->canedit){

			if($arrs!=null&&count($arrs)>0){
				foreach ($arrs as $v){
					$sql="SELECT ws_gid,ws_volume FROM zys_waybill_sub_trunk WHERE ws_tid=".$v;
					$status=$db->getRow($sql);
					if($status&&$status['ws_gid']&&$status['ws_volume']){
						$sql="UPDATE zys_goods_trunk SET g_volume=g_volume+".$status['ws_volume']." WHERE g_tid=".$status['ws_gid'];
						$db->query($sql);
					}
				}
			}else{
				$sql="SELECT ws_gid FROM zys_waybill_sub_trunk WHERE ws_tid=".$arr;
				$status=$db->getRow($sql);
				if($status&&$status['ws_gid']&&$status['ws_volume']){
					$sql="UPDATE zys_goods_trunk SET g_volume=g_volume+".$status['ws_volume']." WHERE g_tid=".$status['ws_gid'];
					$db->query($sql);
				}
			}


			if (!$s_mod->drop($arrs))
			{
				$this->show_warning($s_mod->get_error(),'',    'index.php?app=waybillless&act=edit&id='.$id);

				return;
			}

			if($id>0){
				$sql="UPDATE zys_waybill_main w LEFT JOIN
(SELECT GROUP_CONCAT(ws_ship) as ws_ship,GROUP_CONCAT(ws_voyage) as ws_voyage,GROUP_CONCAT(ws_awb_code) as ws_awb_code,ws_wmtid 
FROM zys_waybill_sub_trunk WHERE ws_wmtid=".$id." GROUP BY ws_wmtid) x on w.wm_tid=x.ws_wmtid 
SET w.wm_ship=x.ws_ship,w.wm_voyage=x.ws_voyage,w.wm_awb_code=x.ws_awb_code WHERE w.wm_tid=".$id;
				$db->query($sql);

				$sql="UPDATE zys_waybill_main SET wm_version=wm_version+1 WHERE wm_tid=".$id;
				$db->query($sql);
			}


			$this->show_message('删除成功',

                '返回明细',    'index.php?app=waybillless&act=edit&id='.$id
			);
		}else{
			$this->show_warning('不能删除此数据', '',    'index.php?app=waybillless&act=edit&id='.$id);
		}
	}

	function dropsubn()
	{
		$db=&db();
		$id = empty($_GET['wid']) ? 0 : intval($_GET['wid']);
		$waybill=$this->_waybill_mod->get(array(
	        'fields'   => 'this.*',
	        'conditions'  => 'wm_tid='.$id,
		));
		if($waybill['wm_stauts']=='新建'||$waybill['wm_stauts']=='已接单'||$waybill['wm_stauts']=='已派'){
			$this->canedit=true;
		}
		$s_mod =& m('waybillnormal');
		$arr = isset($_GET['id']) ? trim($_GET['id']) : '';


		$arrs=explode(',', $arr);
		if($this->canedit){

			if($arrs!=null&&count($arrs)>0){
				foreach ($arrs as $v){
					$sql="SELECT ws_gid,ws_piece,ws_weight,ws_size FROM zys_waybill_sub_normal WHERE ws_tid=".$v;
					$status=$db->getRow($sql);
					if($status&&$status['ws_gid']){
						$sql="UPDATE zys_goods_normal SET g_piece=g_piece+ifnull(".$status['ws_piece'].",0),
						g_weight=g_weight+ifnull(".$status['ws_weight'].",0),g_size=g_size+ifnull(".$status['ws_size'].",0) WHERE g_tid=".$status['ws_gid'];
						$db->query($sql);
					}
				}
			}else{
				$sql="SELECT ws_gid,ws_piece,ws_weight,ws_size FROM zys_waybill_sub_normal WHERE ws_tid=".$arr;
				$status=$db->getRow($sql);
				if($status&&$status['ws_gid']&&$status['ws_volume']){
					$sql="UPDATE zys_goods_normal SET g_piece=g_piece+ifnull(".$status['ws_piece'].",0),
						g_weight=g_weight+ifnull(".$status['ws_weight'].",0),g_size=g_size+ifnull(".$status['ws_size'].",0) WHERE g_tid=".$status['ws_gid'];
					$db->query($sql);
				}
			}


			if (!$s_mod->drop($arrs))
			{
				$this->show_warning($s_mod->get_error()  , '',    'index.php?app=waybillless&act=edit&id='.$id);


				return;
			}


			if($id>0){
				$sql="UPDATE zys_waybill_main w LEFT JOIN
(SELECT GROUP_CONCAT(ws_piece) as ws_piece,GROUP_CONCAT(ws_weight) as ws_weight,GROUP_CONCAT(ws_size) as ws_size,ws_wmtid 
FROM zys_waybill_sub_normal WHERE ws_wmtid=".$id." GROUP BY ws_wmtid) x on w.wm_tid=x.ws_wmtid 
SET w.wm_piece=x.ws_piece,w.wm_weight=x.ws_weight,w.wm_size=x.ws_size WHERE w.wm_tid=".$id;
				$db->query($sql);

				$sql="UPDATE zys_waybill_main SET wm_version=wm_version+1 WHERE wm_tid=".$id;
				$db->query($sql);
			}

			$this->show_message('删除成功',

                '返回明细',    'index.php?app=waybillless&act=edit&id='.$id
			);
		}else{
			$this->show_warning('不能删除此数据',  '',    'index.php?app=waybillless&act=edit&id='.$id);
		}

	}
	//货物列表
	function choosegoods(){
		$goodsnormalsub=& m('goodsnormalsub');
		$page = $this->_get_page();

		$wm_code=empty($_GET['code'])?'':$_GET['code'];
		$this->assign('wm_code', $wm_code);

		$wmid=empty($_GET['wmid'])?0:$_GET['wmid'];
		$this->assign('wmid', $wmid);

		$t=empty($_GET['t'])?'零担':$_GET['t'];
		$sql="SELECT count(1)
		from zys_goods_normal_sub s LEFT JOIN zys_goods_normal n ON s.gs_gtid=n.g_tid 
		WHERE (s.gs_piecep<s.gs_piece OR s.gs_weightp<s.gs_weight OR s.gs_sizep<s.gs_size) AND n.g_type='零担' 
		AND s.g_carrier!=".$this->visitor->get('unit')."";
		$page['item_count'] = $goodsnormalsub->getOne($sql);

		$this->_format_page($page);
		$this->assign('page_info', $page);

		$sql="SELECT s.*,n.*,IFNULL(s.gs_weight-s.gs_weightp,0) AS weights,
		IFNULL(s.gs_piece-s.gs_piecep,0) AS pieces,IFNULL(s.gs_size-s.gs_sizep,0) AS sizes 
		from zys_goods_normal_sub s LEFT JOIN zys_goods_normal n ON s.gs_gtid=n.g_tid 
		WHERE (s.gs_piecep<s.gs_piece OR s.gs_weightp<s.gs_weight OR s.gs_sizep<s.gs_size) AND n.g_type='零担' 
		and not exists(select 1 from zys_waybill_sub_normal where ws_new=0 AND ws_gstid=gs_tid)
		AND s.g_carrier!=".$this->visitor->get('unit')." limit $page[limit]";
		$goods=$goodsnormalsub->getAll($sql);
		$this->assign('goods', $goods);

		$this->display('waybill.less.choosegoods.html');
	}
	//引入货物
	function choosegoodsdone(){

		$db=&db();

		$piecearrs = isset($_POST['piecenum']) ? $_POST['piecenum'] : '';
		$weightarrs = isset($_POST['weightnum']) ? $_POST['weightnum'] : '';
		$sizearrs = isset($_POST['sizenum']) ? $_POST['sizenum'] : '';

		$checkarrs = isset($_POST['cnum']) ? $_POST['cnum'] : '';

		$wmid=isset($_POST['wm_tid']) ? $_POST['wm_tid'] : '';
		$c=empty($_POST['wm_code'])?'':$_POST['wm_code'];

		if($checkarrs!=null&&count($checkarrs)>0){
			if(empty($wmid)){

				//新建零担运单
				$sql="INSERT INTO zys_waybill_main (wm_type,wm_stauts,wm_code,wm_optid,wm_opdate)
				VALUES('零担','新建','".$c."','".$this->visitor->get('user_id')."','".gmtime()."')";
				$db->query($sql);
				$wmid=$db->insert_id();
			}
			if($wmid){
				foreach ($checkarrs as $k=>$v){
					$sql="select s.*,t.g_type from zys_goods_normal_sub s left join zys_goods_normal t on s.gs_gtid=t.g_tid where gs_tid=".$k;
					$info=$db->getRow($sql);

					if($info&&$info['gs_gtid']){
						//运单子表写入数据
						$sql="INSERT INTO zys_waybill_sub_normal (ws_wmtid,ws_gid,ws_gstid,ws_piece,ws_weight,ws_size,ws_new)
						VALUES($wmid,".$info['gs_gtid'].",$k,'".$piecearrs[$k]."','".$weightarrs[$k]."','".$sizearrs[$k]."',1)";	
						$db->query($sql);

						//统计当前货物 件 已派数量
						$sql="SELECT SUM(ws_piece) from zys_waybill_sub_normal WHERE ws_gstid=$k";
						$pnum=$db->getOne($sql);

						//统计当前货物 重 已派数量
						$sql="SELECT SUM(ws_weight) from zys_waybill_sub_normal WHERE ws_gstid=$k";
						$wnum=$db->getOne($sql);

						//统计当前货物 尺 已派数量
						$sql="SELECT SUM(ws_size) from zys_waybill_sub_normal WHERE ws_gstid=$k";
						$snum=$db->getOne($sql);


						//更新货物子表数据
						$sql="UPDATE zys_goods_normal_sub SET gs_piecep='".$pnum."',gs_weightp='".$wnum."',gs_sizep='".$snum."' WHERE gs_tid=$k";
						$db->query($sql);

					}

				}
			}

		}
		echo("<script>window.parent.location.href='index.php?app=waybillless&act=edit&id=".$wmid."';</script>");
	}

	function addhauldeploy($hid,$h_wmtid)
	{
		$db=&db();

		$sql="delete from zys_haul_collect where exists(select 1 from zys_haul where hc_h_tid=h_tid and h_wmtid=".$h_wmtid.")";
		$db->query($sql);

		$sql="delete from zys_haul where h_wmtid=".$h_wmtid;
		$db->query($sql);

		$sql="SELECT * FROM zys_haul_define WHERE h_zhdmtid='".$hid."'";
		$temp=$db->getAll($sql);

		if($temp){
			foreach ($temp as $v){
				if($v['h_address']=='@L_load' || $v['h_address']=='@L_unload' || $v['h_linkman']=='@L_fhr' || $v['h_linkman']=='@L_shr' || $v['h_linkman_tel']=='@L_linktel' || $v['h_linkman_tel']=='@L_fhr_tel' || $v['h_linkman_tel']=='@L_shr_tel'
					|| $v['h_date']=='@L_load_time' || $v['h_date']=='@L_unload_time' ){
					$sql = "select gn.g_loading_date,gn.g_unloading_date,gn.g_owner_tel,gn.g_loading_place,gn.g_loading_lng,gn.g_loading_lat,gn.g_unloading_place,gn.g_unloading_lng,gn.g_unloading_lat,gn.g_consignee,gn.g_consignee_tel,gn.g_consignor,gn.g_consignor_tel from zys_goods_normal as gn left join zys_waybill_sub_normal as wsn on gn.g_tid= wsn.ws_gid where wsn.ws_wmtid=".$h_wmtid." GROUP BY ws_gid";
					$row = $db->getrow($sql);
					switch($v['h_linkman']){
						case '@L_fhr':
							$data['h_linkman'] = $row['g_consignor'];
							break;
						case '@L_shr':
							$data['h_linkman'] = $row['g_consignee'];
							break;
						default:
							$data['h_linkman'] = $v['h_linkman'];
							break;
					}
					switch($v['h_linkman_tel']){
						case '@L_linktel':
							$data['h_linkman_tel'] = $row['g_owner_tel'];
							break;
						case '@L_fhr_tel':
							$data['h_linkman_tel'] = $row['g_consignor_tel'];
							break;
						case '@L_shr_tel':
							$data['h_linkman_tel'] = $row['g_consignee_tel'];
							break;
						default:
							$data['h_linkman_tel'] = $v['h_linkman_tel'];
							break;
					}
					switch($v['h_address']){
						case '@L_load':
							$data['h_address'] = $row['g_loading_place'];
							$data['h_lng'] = $row['g_loading_lng'];
							$data['h_lat'] = $row['g_loading_lat'];
							break;
						case '@L_unload':
							$data['h_address'] = $row['g_unloading_place'];
							$data['h_lng'] = $row['g_unloading_lng'];
							$data['h_lat'] = $row['g_unloading_lat'];
							break;
						default:
							$data['h_address'] = $v['h_address'];
							break;
					}
					switch($v['h_date']){
						case '@L_load_time':
							$data['h_required_service_date'] = $row['g_loading_date'];
							break;
						case '@L_unload_time':
							$data['h_required_service_date'] = $row['g_unloading_date'];
							break;
						default:
							$data['h_required_service_date'] = $v['h_date'];
							break;
					}

				}else{
					$data['h_address'] = $v['h_address'];
					$data['h_linkman'] = $v['h_linkman'];
					$data['h_linkman_tel'] = $v['h_linkman_tel'];
					$data['h_required_service_date'] = $v['h_date'];
				}

				$data['h_wmtid'] = $h_wmtid;
				$data['h_name'] = $v['h_name'];
				$data['h_short_name'] = $v['h_short_name'];

				$data['h_order'] = $v['h_order'];
				$data['h_type'] = $v['h_type'];
				$data['h_range'] = intval($v['h_range']);

				$id = $this->_haul_mod->add($data);

				$sql="select * from zys_haul_define_collect where hc_h_tid=".$v['h_tid'];
				$collect=$db->getAll($sql);
				if($collect){
					foreach ($collect as $c){
						$sql="insert into zys_haul_collect set hc_h_tid='".$id."',
						h_collect_type='".$c['h_collect_type']."',h_collect_des='".$c['h_collect_des']."',h_collect_val='".$c['h_collect_val']."'";
						$db->query($sql);
					}
				}
			}
		}
	}

	function pcsave() {
		$wid=empty($_POST['wm_tid'])?0:intval($_POST['wm_tid']);
		$wm_driver=empty($_POST['wm_driver'])?'':$_POST['wm_driver'];
		$oper=empty($_POST['operator'])?0:intval($_POST['operator']);
		$wm_vhc_code=empty($_POST['wm_vhc_code'])?'':$_POST['wm_vhc_code'];
		$wm_driver_tel=empty($_POST['wm_driver_tel'])?'':$_POST['wm_driver_tel'];
		$wm_requiredl_note=empty($_POST['wm_requiredl_note'])?'':$_POST['wm_requiredl_note'];
		$wm_requiredl_note_voice=empty($_POST['wm_requiredl_note_voice'])?'':$_POST['wm_requiredl_note_voice'];
		$db=&db();


		$sql="SELECT o_name from zys_operator WHERE o_tid=".$oper;
		$oname=$db->getOne($sql);


		$sql="update zys_waybill_main set wm_vhc_code='".$wm_vhc_code."',wm_driver='".$wm_driver."'
			,wm_driver_tel='".$wm_driver_tel."',wm_carrier='".$oname."'
			,wm_carrier_id=$oper,wm_requiredl_note='".$wm_requiredl_note."',wm_requiredl_note_voice='".$wm_requiredl_note_voice."'
			 where wm_tid=".$wid;
		$db->query($sql);

		$this->show_message('edit_ok',
                '返回运单',   'index.php?app=waybillless&act=edit&id=' . $wid
		);
	}
	/**
	 * 派车处理
	 */
	function paichedone() {
		$db=&db();
		$wid=empty($_GET['wm_tid'])?0:intval($_GET['wm_tid']);
		$uid=empty($_GET['wm_user'])?0:intval($_GET['wm_user']);

		$sql="select * from zys_waybill_main where wm_tid=".$wid;
		$w=$db->getRow($sql);

		$sql="select * from zys_member where user_id=".$uid;
		$user=$db->getRow($sql);
		if(!empty($wid)){
			//修改运单状态
			$sql="UPDATE zys_waybill_main SET wm_stauts='已派' WHERE wm_tid=$wid";
			$db->query($sql);

			//修改运单信息
			$sql="UPDATE zys_waybill_main SET wm_uuid='".$user['uuid']."' WHERE wm_tid=$wid";
			$db->query($sql);


			//发送推送消息
			require_once ROOT_PATH.'/baidupush/sdk.php';
			$sdk = new PushSDK();
			$channelId = $user['channelId']?$user['channelId']:'3849309310203392735';
			try{

				$opts = array (
				'msg_type' => 0
				);
				if($w['wm_type']=='集卡进口 ') {
					$sql="select * from zys_goods_trunk where exists(select 1 from zys_waybill_sub_trunk where g_tid=ws_gid and ws_wmtid=".$wid.")";
					$gt=$db->getRow($sql);

					$rs = $sdk->pushMsgToSingleDevice($channelId,
						'{"type":"3","result":{"wm_tid":"' . $wid . '","type":"' . $w['wm_type'] . '","note":"' . $w['wm_requiredl_note'] . ' ' . local_date('Y年m月d日 H点i分', $gt['g_collectiontime']) . '到' . $gt['g_full_container_depot'] . '背重箱
				' . local_date('Y年m月d日 H点i分', $gt['g_packingtime']) . '送至' . $gt['g_loading_place'] . '","voice":"' . $w['wm_requiredl_note_voice'] . '","intral":"30"}}', $opts);
				}
				else if($w['wm_type']=='集卡出口 ') {
					$sql="select * from zys_goods_trunk where exists(select 1 from zys_waybill_sub_trunk where g_tid=ws_gid and ws_wmtid=".$wid.")";
					$gt=$db->getRow($sql);

					$rs = $sdk->pushMsgToSingleDevice($channelId,
						'{"type":"3","result":{"wm_tid":"' . $wid . '","type":"' . $w['wm_type'] . '","note":"' . $w['wm_requiredl_note'] . ' ' . local_date('Y年m月d日 H点i分', $gt['g_packingtime']) . '到' . $gt['g_loading_place'] . '装货
				' . local_date('Y年m月d日 H点i分', $gt['g_collectiontime']) . '前送至' . $gt['g_full_container_depot'] . '","voice":"' . $w['wm_requiredl_note_voice'] . '","intral":"30"}}', $opts);
				}
				else{
					$sql="select * from zys_goods_normal where exists(select 1 from zys_waybill_sub_normal where g_tid=ws_gid and ws_wmtid=".$wid.") order by g_opdate desc limit 1";
					$gt=$db->getRow($sql);

					if($gt){
						$rs = $sdk->pushMsgToSingleDevice($channelId,
						'{"type":"3","result":{"wm_tid":"' . $wid . '","type":"' . $w['wm_type'] . '","note":"' . $w['wm_requiredl_note'] . ' ' . local_date('Y年m月d日 H点i分', $gt['g_loading_date']) . '到' . $gt['g_loading_place'] . '提货
				' . local_date('Y年m月d日 H点i分', $gt['g_unloading_date']) . '送至' . $gt['g_unloading_place'] . '","voice":"' . $w['wm_requiredl_note_voice'] . '","intral":"30"}}', $opts);
					}
				}
			}catch (Exception $ex){

			}
		}

		$this->show_message('派车成功',
                '返回运单',   'index.php?app=waybillless&act=edit&id=' . $wid
		);

	}
	/**
	 * 异常处理
	 */
	function exceptiondone() {
		$db=&db();
		$wid=empty($_POST['wm_tid'])?0:intval($_POST['wm_tid']);
		$exp=empty($_POST['exp'])?array():$_POST['exp'];

		if($exp){
			$exp=array_values($exp);
			foreach ($exp as $k=>$v){
				if($v['e_tid']){
					$sql="UPDATE zys_exception SET e_staus='已处理',e_handle_person='".$v['e_handle_person']."'
					,e_handle_date='".gmstr2time($v['e_handle_date'])."',e_handle_note='".$v['e_handle_note']."' WHERE e_tid=".$v['e_tid']."";

					$db->query($sql);
				}
			}
		}

		$this->show_message('处理成功',
                '返回运单',   'index.php?app=waybillless&act=edit&id=' . $wid
		);
	}

	//加入到地址管理系统中

	function addaddr($data){
		$addr = & m('addr');
		$addr->add($data);
	}

	//验证地址是否已经存在
	function checkaddr($addr,$userid,$unit){
		$db = &db();
		$sql="select count(*) as num from zys_addr where address='".$addr."' and user_id=".$userid." and unit=".$unit;
		$num = $db->getone($sql);
		return $num;
	}
}